import Vue from 'vue'
import VueRouter from 'vue-router'

import Login from '@/views/Login.vue'

import Teacher from '@/views/Teacher.vue'
import TeacherAction from '@/components/teacher/TeacherAction'
import TeacherCourse from '@/components/teacher/TeacherCourse'

import Student from '@/views/Student.vue'
import StudentAction from '@/components/student/StudentAction'
import StudentCourse from '@/components/student/StudentCourse'

import Admin from '@/views/Admin.vue'
import AdminStudent from '@/components/admin/AdminStudent'
import AdminTeacher from '@/components/admin/AdminTeacher'

Vue.use(VueRouter)

const routes = [
  { path: '', redirect: '/login' },
  { path: '/login', component: Login },
  {
    path: '/teacher',
    component: Teacher,
    children: [
      { path: 'course', component: TeacherCourse },
      { path: 'Action', component: TeacherAction }
    ]
  },
  {
    path: '/student',
    component: Student,
    children: [
      { path: 'course', component: StudentCourse },
      { path: 'Action', component: StudentAction }
    ]
  },
  {
    path: '/admin',
    component: Admin,
    children: [
      { path: 'student', component: AdminStudent },
      { path: 'teacher', component: AdminTeacher }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 前置守卫，判断是否违法登录
router.beforeEach((to, from, next) => {
  const firstPath = to.path.split('/')[1]

  if (firstPath === 'admin' || firstPath === 'teacher' || firstPath === 'student') {
    if (!localStorage.getItem('token') || firstPath !== localStorage.getItem('token').split('/')[0]) {
      next('/login')
    }
  }
  next()
})

export default router
